// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var constant = require("constant");
	var router = require("../hash/pageRouter");
	var fileUuid = [];
	var expenseType = 1;
	var css_product = require("./productCharge.css");
	var html_add_charge = require("./productCharge_add.html");
	var html_warningScheme_list = require("./html_warningScheme_list.html");
	var tools = require("tools");
	var productId;
	var schemeIds = [];
	var oData1 = {
		pageSize: 10000
	};
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var init = function(page) {
		productId = page.params.productId;
		inquireFinanceProductDetail();
		inquireFinanceProductExpensePageList();
		initEvent();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}

		$("#chargeNext").click(function() {
			router.route("productManage/productManage.html");
		});

		$(".chargeNav a").click(function() {
			expenseType = $(this).attr("expenseType");
			$(".chargeNav a").removeClass("chargeNavActive");
			$(this).addClass("chargeNavActive");
			$(".chargeContent").addClass("none");
			$("." + $(this).attr("id")).removeClass("none");
		});

		$("#chargeBack").unbind("click").click(function() {
			router.route("productManage/productAdd.html?productId=" + productId);
		});

		$("#addChargeBtn").on("click", function() {
			if (expenseType == 4) {
				$("#popdialog").html(html_warningScheme_list);
				$("#scheme_list_dialog input[name=productId]").val(productId);
				
				tools.loadList("inquireWarningSchemePageList.json", $("#htmlSchemeListTable"), $("#htmlSchemeListTpl"), oData1, function(){
					$.each($("#scheme_list_dialog tr"), function() {
						var $othis = $(this);
						$.each(schemeIds, function(){
							var ithis = this;
							if ($othis.attr("schemeId") == ithis) {
								$othis.find("input[type=checkbox]").prop("checked", true);
							}
						});
					});
					
					$("#scheme_list_dialog .schemes").html("");
					$.each($("#scheme_list_dialog .schemeCheck:checked"), function() {
						var str = '<input type="hidden" name="schemeId" value="'+ $(this).parents("tr").attr("schemeId") +'" />';
						$("#scheme_list_dialog .schemes").append(str);
					});
				});
				
//				查询按钮
				$("#scheme_list_dialog #schemeListSearchButton").unbind("click").click(function(){
					oData1.startDate = $("#scheme_list_dialog .startDate").val();
					oData1.endDate = $("#scheme_list_dialog .endDate").val();
					oData1.factor = $("#scheme_list_dialog .factor").val();
					tools.loadList("inquireWarningSchemePageList.json", $("#htmlSchemeListTable"), $("#htmlSchemeListTpl"), oData1, function(){
						$.each($("#scheme_list_dialog tr"), function() {
							var $othis = $(this);
							$.each(schemeIds, function(){
								var ithis = this;
								if ($othis.attr("schemeId") == ithis) {
									$othis.find("input[type=checkbox]").prop("checked", true);
								}
							});
						});
					});
				});
				
				$("#scheme_list_dialog").on("click", ".schemeCheckAll", function(){
					if ($(this).prop("checked")) {
						$("#scheme_list_dialog .schemeCheck").prop("checked", true);
					} else {
						$("#scheme_list_dialog .schemeCheck").prop("checked", false);
					}
					
					$("#scheme_list_dialog .schemes").html("");
					$.each($("#scheme_list_dialog .schemeCheck:checked"), function() {
						var str = '<input type="hidden" name="schemeId" value="'+ $(this).parents("tr").attr("schemeId") +'" />';
						$("#scheme_list_dialog .schemes").append(str);
					});
				});
				
				$("#scheme_list_dialog").on("click", ".schemeCheck", function(){
					if ($("#scheme_list_dialog .schemeCheck").length == $("#scheme_list_dialog .schemeCheck:checked").length) {
						$("#scheme_list_dialog .schemeCheckAll").prop("checked", true);
					} else {
						$("#scheme_list_dialog .schemeCheckAll").prop("checked", false);
					}
					
					$("#scheme_list_dialog .schemes").html("");
					$.each($("#scheme_list_dialog .schemeCheck:checked"), function() {
						var str = '<input type="hidden" name="schemeId" value="'+ $(this).parents("tr").attr("schemeId") +'" />';
						$("#scheme_list_dialog .schemes").append(str);
					});
				});
				
				dialog.showDialog($("#scheme_list_dialog"));
				
				$("#scheme_list_dialog .sure_yes").unbind("click").click(function(){
					databind.submitDom($("#scheme_list_dialog"), function(){
						base.alert(1, "添加成功！");
						dialog.hideDialog($("#scheme_list_dialog"));
						router.route("productManage/productCharge.html?productId=" + productId);
					});
				});
				
				$("#scheme_list_dialog .sure_no").unbind("click").click(function(){
					dialog.hideDialog($("#scheme_list_dialog"));
				});
				
				return;
			}
			
			$("#popdialog").html(html_add_charge);
			if ($("#expenseMethod").val() == '1') {
				$(".inventoryInfo").removeClass("none");
				$(".bulkstockInfo").addClass("none");
			} else if ($("#expenseMethod").val() == '3') {
				$(".bulkstockInfo").removeClass("none");
				$(".inventoryInfo").addClass("none");
			} else if ($("#expenseMethod").val() == '2') {
				$(".inventoryInfo").addClass("none");
				$(".bulkstockInfo").addClass("none");
			}
			dialog.showDialog($("#add_charge_dialog"));
			tools.requireInput($("#add_charge_dialog"));
			$(".expenseType").val(expenseType);
			if (expenseType == 1) {
				$(".dialogTitle").html("提前罚息");
				$(".chargeType1").removeClass("none");
				$(".chargeType2").addClass("none");
			} else if (expenseType == 2) {
				$(".dialogTitle").html("延期计息");
				$(".chargeType1").removeClass("none");
				$(".chargeType2").addClass("none");
			} else if (expenseType == 3) {
				$(".dialogTitle").html("费用项目");
				$(".chargeType2").removeClass("none");
				$(".chargeType1").addClass("none");
			}
			$(".productId").val(productId);

			autoComplete1();
			autoComplete2();

			$(".chargeDelete").unbind("click").click(function() {
				deleteFinanceProductExpense($(this).parents("tr").attr("productExpenseId"));
			});

			$("#chargeCancel").unbind("click").click(function() {
				dialog.hideDialog($("#add_charge_dialog"));
			});

			$("#expenseMethod").on("change", function() {
				if ($("#expenseMethod").val() == '1') {
					$(".inventoryInfo").removeClass("none");
					$(".bulkstockInfo").addClass("none");
				} else if ($("#expenseMethod").val() == '3') {
					$(".bulkstockInfo").removeClass("none");
					$(".inventoryInfo").addClass("none");
				} else {
					$(".inventoryInfo").addClass("none");
					$(".bulkstockInfo").addClass("none");
				}
			});
			$("#chargeSure").unbind("click").click(function() {
				if (parseInt($("#chargeAddStartDate").val()) > parseInt($("#chargeAddEndDate").val())) {
					base.alert(2, "开始时间不能大于截止时间！");
				} else {
					if (expenseType == 3) {
						if($("#expenseMethod").val() == '1'){
							$(".bulkstockInfo").remove();
						}else if ($("#expenseMethod").val() == '3'){
							$(".inventoryInfo").remove();
						}else{
							$(".inventoryInfo").remove();
							$(".bulkstockInfo").remove();
						}
						databind.submitDom($(".chargeType2"), function() {
							base.alert(1, "费用添加成功！");
							dialog.hideDialog($("#add_charge_dialog"));
							inquireFinanceProductDetail();
							inquireFinanceProductExpensePageList();
						});
					} else if ($("#chargeAddStartAmount").val() > 100) {
						base.alert(2, "费率不能超过100！");
					} else {
						databind.submitDom($(".chargeType1"), function() {
							base.alert(1, "费用添加成功！");
							dialog.hideDialog($("#add_charge_dialog"));
							inquireFinanceProductDetail();
							inquireFinanceProductExpensePageList();
						});
					}
				}
			});
		});
	};

	var autoComplete = function(bulkstockCategoryId) {
		//自动补全
		$("#chargeBulkstockName").autocomplete(seajs.data.handler + "inquireBulkstockPageList.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid"),
				bulkstockCategoryId: bulkstockCategoryId
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.bulkstockName, //此处无需把全部列列出来，只是两个关键列
						result: row.bulkstockName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#chargeBulkstockName").hasClass('nonemorelist')) {
					$("#chargeBulkstockName").removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.bulkstockName + "(" + data.specificationName + ")" + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.bulkstockName;
			},
			formatResult: function(data, value) {
				return data.bulkstockName;
			}
		}).result(function(event, data, formatted) { //回调
			$('#chargeBulkstockName').val(data.bulkstockName);
			if ($("#chargeBulkstockName").hasClass('nonemorelist')) {
				$("#chargeBulkstockName").removeClass('nonemorelist');
			} else {
				$("#chargeBulkstockName").addClass('nonemorelist');
			};
			$("#chargeBulkstockId").val(data.bulkstockInfoId);
		});
	};
	
	var autoComplete3 = function(bulkstockCategoryId) {
		//自动补全
		$("#chargeBulkstockName1").autocomplete(seajs.data.handler + "inquireBulkstockPageList.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid"),
				bulkstockCategoryId: bulkstockCategoryId
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.bulkstockName, //此处无需把全部列列出来，只是两个关键列
						result: row.bulkstockName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#chargeBulkstockName1").hasClass('nonemorelist')) {
					$("#chargeBulkstockName1").removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.bulkstockName + "(" + data.specificationName + ")" + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.bulkstockName;
			},
			formatResult: function(data, value) {
				return data.bulkstockName;
			}
		}).result(function(event, data, formatted) { //回调
			$('#chargeBulkstockName1').val(data.bulkstockName);
			if ($("#chargeBulkstockName1").hasClass('nonemorelist')) {
				$("#chargeBulkstockName1").removeClass('nonemorelist');
			} else {
				$("#chargeBulkstockName1").addClass('nonemorelist');
			};
			$("#chargeBulkstockId1").val(data.bulkstockInfoId);
		});
	};

	var autoComplete1 = function() {
		//自动补全
		$("#chargecategoryName").autocomplete(seajs.data.handler + "inquireBulkstockCategoryPageListByKeyword.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid")
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.categoryName, //此处无需把全部列列出来，只是两个关键列
						result: row.categoryName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#chargecategoryName").hasClass('nonemorelist')) {
					$("#chargecategoryName").removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.categoryName + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.categoryName;
			},
			formatResult: function(data, value) {
				return data.categoryName;
			}
		}).result(function(event, data, formatted) { //回调
			$('#chargecategoryName').val(data.categoryName);
			if ($("#chargecategoryName").hasClass('nonemorelist')) {
				$("#chargecategoryName").removeClass('nonemorelist');
			} else {
				$("#chargecategoryName").addClass('nonemorelist');
			};
			$("#bulkstockCategoryId").val(data.bulkstockCategoryId);
			autoComplete3(data.bulkstockCategoryId);
		});
	};
	
	var autoComplete2 = function() {
		//自动补全
		$("#chargecategoryName1").autocomplete(seajs.data.handler + "inquireBulkstockCategoryPageListByKeyword.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid")
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.categoryName, //此处无需把全部列列出来，只是两个关键列
						result: row.categoryName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#chargecategoryName1").hasClass('nonemorelist')) {
					$("#chargecategoryName1").removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.categoryName + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.categoryName;
			},
			formatResult: function(data, value) {
				return data.categoryName;
			}
		}).result(function(event, data, formatted) { //回调
			$('#chargecategoryName1').val(data.categoryName);
			if ($("#chargecategoryName1").hasClass('nonemorelist')) {
				$("#chargecategoryName1").removeClass('nonemorelist');
			} else {
				$("#chargecategoryName1").addClass('nonemorelist');
			};
			$("#bulkstockCategoryId1").val(data.bulkstockCategoryId);
			autoComplete(data.bulkstockCategoryId);
		});
	};

	// 查询产品明细
	var inquireFinanceProductDetail = function() {
		base.fnAjax({
			action: "inquireFinanceProductDetail.json", //接口名称
			oData: {
				productId: productId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					schemeIds = data.datas[0].schemeIds;
					juicer.register("getValueByKey", constant.getValueByKey);
					var tpl = $("#chargeListTpl1").html();
					var html = juicer(tpl, data);
					$("#chargeListBody1").html(html);
					var tpl = $("#chargeListTpl2").html();
					var html = juicer(tpl, data);
					$("#chargeListBody2").html(html);
					var tpl = $("#chargeListTpl4").html();
					var html = juicer(tpl, data);
					$("#chargeListBody4").html(html);
					if (data.datas.length == 0) {

					}

					$(".chargeDelete").unbind("click").click(function() {
						deleteFinanceProductExpense($(this).parents("tr").attr("productExpenseId"));
					});
					
					//预警方案详情
					$(".schemeDetail").unbind("click").click(function() {
						router.route("auditWarning/warningSchemeCreate.html?schemeId=" + $(this).parents("tr").attr("schemeId"));
					});
					
					//删除预警方案
					$(".schemeDelete").unbind("click").click(function() {
						var $this = $(this);
						dialog.showConfirmDialog("删除", "是否删除该条预警方案？", function(){
							removeProductWarningScheme($this.parents("tr").attr("productId"), $this.parents("tr").attr("schemeId"));
					});
						});
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 查询产品费用列表
	var inquireFinanceProductExpensePageList = function() {
		base.fnAjax({
			action: "inquireFinanceProductExpensePageList.json", //接口名称
			oData: {
				productId: productId,
				pageSize: pageSize,
				pageIndex: pageIndex
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					juicer.register("getValueByKey", constant.getValueByKey);
					var tpl = $("#chargeListTpl3").html();
					var html = juicer(tpl, data);
					$("#chargeListBody3").html(html);
					totalPageCount = data.totalPageCount;
					totalRecordCount = data.totalRecordCount;
					base.pageControl($("#chargePage"),
						totalRecordCount,
						data.pageIndex,
						data.pageSize,
						function(p) {
							pageIndex = p;
							inquireFinanceProductExpensePageList();
						});
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 查询产品费用列表
	var deleteFinanceProductExpense = function(productExpenseId) {
		base.fnAjax({
			action: "deleteFinanceProductExpense.json", //接口名称
			oData: {
				productExpenseId: productExpenseId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "费用删除成功!");
					router.route("productManage/productCharge.html?productId=" + productId);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 删除产品预警方案
	var removeProductWarningScheme = function(productId, schemeId) {
		base.fnAjax({
			action: "removeProductWarningScheme.json", //接口名称
			oData: {
				productId: productId,
				schemeId: schemeId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "删除成功!");
					router.route("productManage/productCharge.html?productId=" + productId);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	return {
		init: init
	};
});